﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using DoubleH.Utility;
using System.Collections;
using System.Windows.Controls.Primitives;
using System.ComponentModel;
using Table = FCNS.Data.Table;
using System.Diagnostics;
using System.Xml.Linq;
using System.Xml;
using System.Windows.Markup;
using DoubleH.Utility.Configuration;
using System.Reflection;

namespace DoubleH.Utility.UC.PagePanel
{
    /// <summary>
    /// PageListView.xaml 的交互逻辑
    /// </summary>
    public partial class PageListView : Page,IPagePanel
    {
        public enum EnumModeTemplete
        {
            /// <summary>
            /// 表示不支持缩略图功能
            /// </summary>
            Null,
            PosProductSItemTemplateHaveImgAndText,
            PosProductSItemTemplateNoImg,
            PosProductSItemTemplateNoText,

            BodyItemTemplateHaveImgAndText,
            HeaderItemTemplateHaveImgAndText
        }

        public PageListView()
        {
            InitializeComponent();

            InitEvent();
        }
        
        public event Utility.UC.UCPagePanel.dDoubleClickItem ItemDoubleClick;
        public event Utility.UC.UCPagePanel.dClickItem ItemClick;
        public event Utility.UC.UCPagePanel.dHyperlinkClickItem HyperlinkClick;
        public event Utility.UC.UCPagePanel.dScrollMove ScrollMove;

        protected bool m_IsDraging = false;
        protected Point m_DragStartPoint;
        IList<Table.GroupS> groups = null;
        IList items = null;
        IList homeData = null;

        private void InitEvent()
        {
            pulseButtonHome.Click += (ss, ee) => GoHome();
            pulseButtonHome.PreviewDrop += (ss, ee) => DropEnd(ee);

            listViewExtHeader.MouseDoubleClick += (ss, ee) => ChangedGroup();
            listViewExtHeader.SelectionChanged += (ss, ee) => listViewExtHeaderSelectionChanged();

            listViewExtBody.MouseDoubleClick += (ss, ee) => ListViewExtMouseDoubleClick();
            listViewExtBody.PreviewMouseLeftButtonDown += (ss, ee) => DropStart(ee);
            listViewExtBody.PreviewMouseMove += (ss, ee) => DropMove(ee);
            listViewExtBody.PreviewMouseLeftButtonUp += (ss, ee) => listViewExtBody.SelectedItem = null;//如果不这样就无法拖动滚动条了
            CommandManager.AddPreviewExecutedHandler(listViewExtBody, new ExecutedRoutedEventHandler(OnScorllMove));
        }

        private void GoHome()
        {
            Table.GroupS gs = pulseButtonHome.Tag as Table.GroupS;
            if (gs == null)
            {
                listViewExtHeader.SelectedItem = null;
                listViewExtBody.ItemsSource = homeData ?? items;
            }
            else
            {
                listViewExtHeader.ItemsSource = this.groups.Where(f => f.GroupSId == gs.GroupSId);
                if (gs.GroupSId == -1)
                {
                    pulseButtonHome.IsPulsing = false;
                                        //pulseButtonHome.Background = new BitmapImage(new Uri(@"Pack://application:,,,/DoubleH.Utility;component/Images/home_64.png"));
                    pulseButtonHome.Tag = null;
                }
                else
                {
                    Table.GroupS tgs = this.groups.First(f => f.Id == gs.GroupSId);
                    pulseButtonHome.Tag = tgs;
                    //imageHome.Source = new BitmapImage(new Uri(tgs._ImageFile));
                }
            }
        }

        private void ChangedGroup()
        {
            if (this.groups == null || listViewExtHeader.SelectedItem == null)
                return;

            Table.GroupS gs = listViewExtHeader.SelectedItem as Table.GroupS;
            if (gs == null)
                return;
            
               var vr = this.groups.Where(f => f.GroupSId == gs.Id);
               if (vr.Count()==0)
                   return;

               listViewExtHeader.ItemsSource = vr;
                pulseButtonHome.Tag = gs;
                pulseButtonHome.IsPulsing = true;

                //if (string.IsNullOrEmpty(gs._ImageFile))
                //    imageHome.Source = new BitmapImage(new Uri(@"Pack://application:,,,/DoubleH.Utility;component/Images/back_64.png"));
                //else
                //    imageHome.Source = new BitmapImage(new Uri(gs._ImageFile));
        }

        private void listViewExtHeaderSelectionChanged()
        {
            if (listViewExtHeader.SelectedItem == null || items == null)
                return;

            Table.GroupS table = listViewExtHeader.SelectedItem as Table.GroupS;
            if (table == null)
                    InitHomeData(items);
            else
            {
                if (items.Count == 0)
                    return;

                List<object> obj = new List<object>();
                Type t = items[0].GetType();
                PropertyInfo pi = t.GetProperty("GroupSId");
                if (pi == null)
                    return;

                foreach (object ob in items)
                    if ((long)pi.GetValue(ob, null) == table.Id)
                        obj.Add(ob);

                listViewExtBody.ItemsSource = obj;
            }
        }

        private void ListViewExtMouseDoubleClick()
        {
            if (listViewExtBody.SelectedItem == null || ItemDoubleClick == null)
                return;

            ItemDoubleClick(listViewExtBody.SelectedItem);
        }

        private void OnScorllMove(object sender, ExecutedRoutedEventArgs e)
        {
            if (ScrollMove != null)
                ScrollMove(sender, e);
        }


        public void ChangeHeaderView(string templetName, string resourceId, int itemSize)
        {
            listViewExtHeader.ChangeView(templetName, resourceId, itemSize);
        }

        public void ChangeBodyView(string templetName, string resourceId, int itemSize)
        {
            listViewExtBody.ChangeView(templetName, resourceId, itemSize);
        }

        private void DropStart(MouseEventArgs ee)
        {
            m_DragStartPoint = ee.GetPosition(null);
        }

        private void DropMove(MouseEventArgs ee)
        {
            if (listViewExtBody.SelectedItem == null)
                return;

            if (ee.LeftButton == MouseButtonState.Pressed && !m_IsDraging)
            {
                Point position = ee.GetPosition(null);

                if (Math.Abs(position.X - m_DragStartPoint.X) > SystemParameters.MinimumHorizontalDragDistance ||
                    Math.Abs(position.Y - m_DragStartPoint.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    m_IsDraging = true;
                    DataObject data = new DataObject(typeof(Table.DataTableS), listViewExtBody.SelectedItem);
                    DragDropEffects de = DragDrop.DoDragDrop(listViewExtBody, data, DragDropEffects.Copy);
                    m_IsDraging = false;
                }
            }
        }

        private void DropEnd(DragEventArgs ee)
        {
            if (homeData == null)
                return;

            var data = ee.Data;
            if (!data.GetDataPresent(typeof(Table.DataTableS)))
                return;

            Table.DataTableS info = data.GetData(typeof(Table.DataTableS)) as Table.DataTableS;
            if (info == null)
                return;

            Table.DataTableS search = homeData.Cast<Table.DataTableS>().FirstOrDefault(f => f.Id == info.Id);
            if (listViewExtHeader.SelectedItem == null && search != null)//如果是在主页状态下拖动，就等于是移除。
                homeData.Remove(search);
            else if (listViewExtHeader.SelectedItem != null && search == null)
                homeData.Add(info);

            StringBuilder sb = new StringBuilder();
            foreach (Table.DataTableS ps in homeData)
                sb.Append(ps.Id + ",");

            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);

            DoubleHConfig.AppConfig.PosCustomProductS = sb.ToString();
            ConfigSerializer.SaveConfig(DoubleHConfig.AppConfig, FCNS.Data.DbDefine.appConfigFile);
        }



        public void Init(UserUIparams userUIparams, params PagePanel.PageListView.EnumModeTemplete[] templeteName )
        {
            if (templeteName == null)
            {
                listViewExtHeader.ChangeView(PagePanel.PageListView.EnumModeTemplete.HeaderItemTemplateHaveImgAndText.ToString(), "headerViewer", 64);
                listViewExtBody.ChangeView(PagePanel.PageListView.EnumModeTemplete.BodyItemTemplateHaveImgAndText.ToString(), "bodyViewer", 120);
            }
            else
            {
                listViewExtHeader.ChangeView(templeteName[0].ToString(), "headerViewer", 64);
                listViewExtBody.ChangeView(templeteName[1].ToString(), "bodyViewer", 120);
            }
        }
        /// <summary>
        /// 设置主页数据
        /// </summary>
        /// <param name="obj"></param>
        public void InitHomeData(IList obj)
        {
            homeData = obj;
            GoHome();
        }

        public void InitData(IList<Table.GroupS> groups, IList obj)
        {
            this.groups = groups;
            if (groups != null)
                listViewExtHeader.ItemsSource = groups.Where(f => f.GroupSId == -1);

            items = obj;
            listViewExtBody.ItemsSource = obj;
        }

        public object SelectedItem
        {
            get
            {
              return listViewExtBody.SelectedItem;
            }
        }

        public object SelectedGroupItem
        {
            get
            {
                    return listViewExtHeader.SelectedItem;
            }
        }

        public IList SelectedItems
        {
            get
            {
             return listViewExtBody.SelectedItems;
            }
        }

        public Brush BackgroundBrush
        {
            set
            {
                listViewExtHeader.Background = value;
                listViewExtBody.Background = value;
            }
        }

        public Brush ForegroundBrush
        {
            set
            {
                listViewExtHeader.Foreground = value;
                listViewExtBody.Foreground = value;
            }
        }
    }
}
